from flask import render_template, url_for, flash, redirect, request
from flask_login import login_required, current_user
from app import db
from app.models import Student, Major
from app.forms import StudentForm
from app.main import main

@main.route('/')
@main.route('/home')
@login_required
def home():
    students = Student.query.all()
    return render_template('index.html', title='首页', students=students)

@main.route('/student/new', methods=['GET', 'POST'])
@login_required
def add_student():
    # 检查是否是管理员
    if current_user.role != 'admin':
        flash('您没有权限执行此操作！', 'danger')
        return redirect(url_for('main.home'))
    form = StudentForm()
    form.major_id.choices = [(major.id, major.name) for major in Major.query.all()]
    
    if form.validate_on_submit():
        student = Student(
            student_id=form.student_id.data,
            name=form.name.data,
            gender=form.gender.data,
            age=form.age.data,
            major_id=form.major_id.data
        )
        db.session.add(student)
        db.session.commit()
        flash('学生信息添加成功！', 'success')
        return redirect(url_for('main.home'))
    return render_template('student_form.html', title='添加学生', form=form, legend='添加学生')

@main.route('/student/<int:student_id>/update', methods=['GET', 'POST'])
@login_required
def update_student(student_id):
    # 检查是否是管理员
    if current_user.role != 'admin':
        flash('您没有权限执行此操作！', 'danger')
        return redirect(url_for('main.home'))
    student = Student.query.get_or_404(student_id)
    form = StudentForm()
    form.major_id.choices = [(major.id, major.name) for major in Major.query.all()]
    
    # 设置初始学号用于验证
    form.student_id_initial = student.student_id
    
    if form.validate_on_submit():
        student.student_id = form.student_id.data
        student.name = form.name.data
        student.gender = form.gender.data
        student.age = form.age.data
        student.major_id = form.major_id.data
        db.session.commit()
        flash('学生信息已更新！', 'success')
        return redirect(url_for('main.home'))
    elif request.method == 'GET':
        form.student_id.data = student.student_id
        form.name.data = student.name
        form.gender.data = student.gender
        form.age.data = student.age
        form.major_id.data = student.major_id
    return render_template('student_form.html', title='编辑学生', form=form, legend='编辑学生')

@main.route('/student/<int:student_id>/delete', methods=['POST'])
@login_required
def delete_student(student_id):
    # 检查是否是管理员
    if current_user.role != 'admin':
        flash('您没有权限执行此操作！', 'danger')
        return redirect(url_for('main.home'))
    student = Student.query.get_or_404(student_id)
    db.session.delete(student)
    db.session.commit()
    flash('学生信息已删除！', 'success')
    return redirect(url_for('main.home'))